package com.sky.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sky.properties.AliOssProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

@Data
@Slf4j
@Component
public class AliOssUtil {
    @Autowired
    private  AliOssProperties aliOssProperties;

    public  String upload(byte[] bytes, String objectName) {
        OSS ossClient = null;
        try {
            // 创建OSSClient实例
            ossClient = new OSSClientBuilder()
                    .build(aliOssProperties.getEndpoint(),
                            aliOssProperties.getAccessKeyId(),
                            aliOssProperties.getAccessKeySecret());

            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
                // 创建PutObject请求
                PutObjectRequest putObjectRequest = new PutObjectRequest(
                        aliOssProperties.getBucketName(),
                        objectName,
                        inputStream);

                // 执行上传
                PutObjectResult result = ossClient.putObject(putObjectRequest);

                // 生成访问地址（有效期为10年示例）
                Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
                StringBuilder urlBuilder = new StringBuilder("https://");
                urlBuilder.append(aliOssProperties.getBucketName())
                        .append(".")
                        .append(aliOssProperties.getEndpoint())
                        .append("/")
                        .append(objectName);

                return urlBuilder.toString();
            }
        } catch (OSSException | ClientException | IOException e) {
            log.error("OSS上传失败：{}", e.getMessage());
            throw new RuntimeException("文件上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}